import React, {useEffect, useRef, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import axios from "axios";

import {Button, Form, Input, message, notification, PageHeader, Select} from "antd";
import NewsEditor from "../../../components/news-manage/NewsEditor";

const { Option } = Select;

export default function NewsUpdate() {
    const [categories, setCategories] = useState([]);
    const newsFormRef= useRef(null);
    const [ newsContent, setNewsContent ]= useState("");

    const location= useLocation();
    const newsId= location.pathname.split('/')[3];
    const navigate= useNavigate();

    useEffect(()=>{
        axios.get('/api/categories').then(response=>{
            setCategories(response.data);
        });
    }, []);

    useEffect(()=>{
        axios.get(`/api/news/${newsId}?_expand=category&_expand=role`).then(response=>{
            // console.log(response.data);
            let data= response.data;
            newsFormRef.current.setFieldsValue(data);
            setNewsContent(data.content);
        });
    }, [newsId]);


    // 保存至草稿箱 或 提交审核
    const handleSaveAudit= (auditState)=>{
        // auditState===0 ? console.log('保存至草稿箱') : console.log('提交审核');

        newsFormRef.current.validateFields().then(res=>{
            if(newsContent.trim()==="" || newsContent.trim()==="<p></p>") {
                message.error('新闻内容不能为空');
            } else {
                axios.patch(`/api/news/${newsId}`, {
                    "title": res.title,  // 新闻标题
                    "categoryId": res.categoryId,  // 新闻分类id
                    "content": newsContent,  // 新闻正文
                    "auditState": auditState,  // 0草稿箱  1待审核  2审核通过  3审核不通过
                }).then(()=>{
                    if(auditState===0) {
                        notification.info({
                            message: `通知`,
                            description: `您可以到草稿箱中查看${res.title}这篇新闻`,
                            placement: 'bottomRight',
                        });
                        navigate('/news-manage/draft');  // 草稿箱
                    } else {
                        notification.info({
                            message: `通知`,
                            description: `您可以到审核列表中查看${res.title}这篇新闻`,
                            placement: 'bottomRight',
                        });
                        navigate('/audit-manage/list');  // 审核列表
                    }
                });
            }

        }).catch(error=>{
            message.error('表单内容不能为空');
        });
    }

    return (
        <div>
            <PageHeader title="更新新闻" onBack={() => navigate('/news-manage/draft')} />

            <div>
                <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} ref={ newsFormRef }>
                    <Form.Item name="title" label="新闻标题" rules={[{ required: true, message: '请输入文章标题' }]}>
                        <Input placeholder="新闻标题" />
                    </Form.Item>
                    <Form.Item name="categoryId" label="新闻分类" rules={[{ required: true, message: '请选择文章分类' }]}>
                        <Select placeholder="新闻分类">
                            {
                                categories.map(item=><Option value={item.id} key={item.id}>{item.value}</Option>)
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item label="新闻内容" rules={[{ required: true }]}>
                        <NewsEditor content={newsContent} getContent={ (htmlContent)=>{
                            // console.log(htmlContent);
                            setNewsContent(htmlContent);
                        }}/>
                    </Form.Item>
                </Form>

                <span>
                    <Button type="primary" style={{margin: '0 10px'}} onClick={()=>handleSaveAudit(0)}>保存草稿</Button>
                    <Button danger style={{margin: '0 10px'}} onClick={()=>handleSaveAudit(1)}>提交审核</Button>
                </span>
            </div>
        </div>
    )

}
